<template>
  <view :class="[extClass, 'search-bar']" @click="clickView">
    <view class="input-com">
      <mp-icon icon="search" size="24" color="#b7b7b7"></mp-icon>
      <input
        v-model="value"
        class="input"
        type="text"
        confirm-type="search"
        :placeholder="placeholder"
        :disabled="disabled"
        :focus="focusBol"
        placeholder-class="placeholder-class"
        @input="input"
        @focus="focus"
        @blur="blur"
        @confirm="search"
      />
      <view v-show="clearIcon" class="clearable" @click="clear">
        <mp-icon icon="close" type="field" size="20" color="#b7b7b7"></mp-icon>
      </view>
    </view>
    <view v-if="showTxt" class="txt" @click="search">搜索</view>
  </view>
</template>

<script>
/**
 * 搜索组件
 */
export default {
  props: {
    // 是否展示搜索按钮
    showTxt: {
      type: Boolean,
      default: true
    },
    // calss
    extClass: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '搜索'
    },
    focusBol: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: '',
      clearIcon: false
    };
  },

  methods: {
    clear() {
      this.value = '';
    },
    focus() {
      if (this.value) {
        this.clearIcon = true;
      } else {
        this.clearIcon = false;
      }
    },
    blur() {
      this.clearIcon = false;
    },
    input() {
      if (this.value) {
        this.clearIcon = true;
      } else {
        this.clearIcon = false;
      }
      this.$emit('input', this.value);
    },
    search() {
      this.$emit('confirm', this.value);
    },
    clickView() {
      this.$emit('click');
    }
  }
};
</script>

<style lang="scss">
.search-bar {
  margin: 24rpx;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  font-size: 32rpx;
  color: rgba(0, 0, 0, 0.9);
  .placeholder-class {
    color: rgba(0, 0, 0, 0.3);
    font-size: 28rpx;
  }
  .input-com {
    display: flex;
    align-items: center;
    flex: 1;
    background: #ffffff;
    padding: 14rpx;
    border-radius: 40rpx;
    position: relative;
  }
  .input {
    flex: 1;
    padding-left: 16rpx;
    padding-right: 60rpx;
  }
  .txt {
    width: 80rpx;
    text-align: center;
    margin-left: 24rpx;
  }
  .clearable {
    width: 40rpx;
    position: absolute;
    z-index: 9;
    right: 20rpx;
  }
}
</style>
